<template>
  <div class="container">
    <div class="row1">
      <div class="div-box div-box1">
        <div class="head">状态</div>
        <div class="content">
          <StatusItem
            :statusValue="statusInfo.fireAlarm"
            activeClassPrefix="active-circle-red"
            label="火警"
          />
          <StatusItem
            :statusValue="statusInfo.isMalfunction"
            activeClassPrefix="active-circle-yellow"
            label="故障"
          />
          <StatusItem
            :statusValue="statusInfo.delayStatus"
            activeClassPrefix="active-circle-primary"
            label="延时"
          />
          <StatusItem
            :statusValue="statusInfo.sysFault"
            activeClassPrefix="active-circle-yellow"
            label="系统故障"
          />
          <StatusItem
            :statusValue="statusInfo.bootUp"
            activeClassPrefix="active-circle-primary"
            label="启动"
          />
          <StatusItem
            :statusValue="statusInfo.mainCircuitWorked"
            activeClassPrefix="active-circle-green"
            label="主电工作"
          />
          <StatusItem
            :statusValue="statusInfo.feedback"
            activeClassPrefix="active-circle-primary"
            label="反馈"
          />
          <StatusItem
            :statusValue="statusInfo.backupCircuitWorked"
            activeClassPrefix="active-circle-green"
            label="备电工作"
          />
          <StatusItem
            :statusValue="statusInfo.isolate"
            activeClassPrefix="active-circle-primary"
            label="屏蔽"
          />
          <StatusItem
            :statusValue="statusInfo.supervise"
            activeClassPrefix="active-circle-primary"
            label="监管"
          />

          <div class="group">
            <div class="title">火警传输：</div>
            <StatusItem
              :statusValue="statusInfo.fireFeedback"
              activeClassPrefix="active-circle-primary"
              label="动作/反馈"
            />
            <StatusItem
              :statusValue="statusInfo.fireIsolate"
              activeClassPrefix="active-circle-yellow"
              label="故障/屏蔽"
            />
          </div>
          <div class="group">
            <div class="title">气体灭火：</div>
            <StatusItem
              :statusValue="statusInfo.sprayRequest"
              activeClassPrefix="active-circle-primary"
              label="喷洒请求"
            />
            <StatusItem
              :statusValue="statusInfo.gasSpraying"
              activeClassPrefix="active-circle-primary"
              label="气体喷洒"
            />
          </div>
          <div class="group">
            <div class="title">声光报警器：</div>
            <StatusItem
              :statusValue="statusInfo.audibleVisualMute"
              activeClassPrefix="active-circle-primary"
              label="消音"
            />
            <StatusItem
              :statusValue="statusInfo.audibleVisualIsolate"
              activeClassPrefix="active-circle-primary"
              label="屏蔽"
            />
            <StatusItem
              :statusValue="statusInfo.audibleVisualFault"
              activeClassPrefix="active-circle-primary"
              label="故障"
            />
          </div>
        </div>
      </div>
      <div class="div-box div-box2">
        <div class="head">
          <div class="head-left">
            <span>基本面板</span>
          </div>
          <div class="head-right">
            <el-button
              type="primary"
              size="mini"
              @click="onAdd(1)"
              v-permission="{ action: 'host:command:add' }"
              >新增</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="onConfig(1)"
              v-if="commandData.list1 && commandData.list1.length"
              v-permission="{ action: 'host:command:config' }"
              >配置</el-button
            >
          </div>
        </div>
        <div class="content">
          <div
            class="group-button"
            v-if="commandData.list1 && commandData.list1.length"
          >
            <div
              class="button-box"
              v-for="item in commandData.list1"
              :key="item.id"
            >
              <el-button
                class="button"
                type="primary"
                size="mini"
                @click="onCommand(item)"
                >{{ item.keyName }}</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="row2">
      <div class="div-box div-box1">
        <div class="head">
          <div class="head-left">
            <span class="title">总线盘</span>
            <div class="dish-box">
              <div
                :class="['dish', list3Active == index ? 'dish-active' : '']"
                v-for="(item, index) in commandData.list3"
                :key="item.id"
                @click="onDish(3, index)"
              >
                {{ index + 1 }}号盘
              </div>
            </div>
          </div>
          <div class="head-right">
            <el-button
              type="primary"
              size="mini"
              @click="onAdd(3)"
              v-permission="{ action: 'host:command:add' }"
              >新增</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="onConfig(3)"
              v-if="
                commandData.list3[list3Active] &&
                commandData.list3[list3Active].length
              "
              v-permission="{ action: 'host:command:config' }"
              >配置</el-button
            >
          </div>
        </div>
        <el-row
          :gutter="10"
          type="flex"
          class="content"
          v-if="
            commandData.list3[list3Active] &&
            commandData.list3[list3Active].length
          "
        >
          <el-col
            :xs="24"
            :sm="24"
            :md="deviceInfo.detectorType === '107' ? 24 : 24"
            :lg="deviceInfo.detectorType === '107' ? 24 : 12"
            :xl="deviceInfo.detectorType === '107' ? 12 : 8"
            v-for="(item, index) in commandData.list3[list3Active]"
            :key="index"
          >
            <div class="item">
              <div class="index">{{ index + 1 }}</div>
              <div v-if="item[0].id">
                <div style="text-align: center">
                  {{ item[0].addressMapping }}
                </div>
                <div class="commands">
                  <div
                    v-for="(item2, index2) in item"
                    :key="index2"
                    class="command"
                  >
                    <div class="status">
                      <StatusItem
                        v-for="(item3, index3) in item2.commandInfos"
                        :key="index3"
                        :statusValue="item3.statusValue"
                        :activeClassPrefix="
                          item3.statusName === '启动' ||
                          item3.statusName === '启用' ||
                          item3.statusName === '反馈'
                            ? 'active-circle-red'
                            : item3.statusName === '停止' ||
                              item3.statusName === '停用' ||
                              item3.statusName === '工作'
                            ? 'active-circle-green'
                            : 'active-circle-yellow'
                        "
                        :label="item3.statusName"
                        :isPanel="true"
                      />
                    </div>
                    <div class="handle">
                      <div
                        class="handle-button"
                        @click="onCommand(item2)"
                        :style="{
                          background:
                            item2.keyName === '启动'
                              ? '#f78989'
                              : item2.keyName === '停止'
                              ? '#67c23a'
                              : '#7367f0',
                        }"
                      >
                        {{ item2.keyName }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="un-config" @click="onConfig">配置</div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="div-box div-box2">
        <div class="head">
          <div class="head-left">
            <span class="title">多线盘</span>
            <div class="dish-box">
              <div
                :class="['dish', list2Active == index ? 'dish-active' : '']"
                v-for="(item, index) in commandData.list2"
                :key="item.id"
                @click="onDish(2, index)"
              >
                {{ index + 1 }}号盘
              </div>
            </div>
          </div>
          <div class="head-right">
            <el-button
              type="primary"
              size="mini"
              @click="onAdd(2)"
              v-permission="{ action: 'host:command:add' }"
              >新增</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="onConfig(2)"
              v-if="
                commandData.list2[list2Active] &&
                commandData.list2[list2Active].length
              "
              v-permission="{ action: 'host:command:config' }"
              >配置</el-button
            >
          </div>
        </div>
        <el-row
          :gutter="10"
          type="flex"
          class="content"
          v-if="
            commandData.list2[list2Active] &&
            commandData.list2[list2Active].length
          "
        >
          <el-col
            :xs="24"
            :sm="24"
            :md="deviceInfo.detectorType === '107' ? 24 : 24"
            :lg="deviceInfo.detectorType === '107' ? 24 : 12"
            :xl="deviceInfo.detectorType === '107' ? 12 : 8"
            v-for="(item, index) in commandData.list2[list2Active]"
            :key="index"
          >
            <div class="item">
              <div class="index">{{ index + 1 }}</div>
              <div v-if="item[0].id">
                <div style="text-align: center">
                  {{ item[0].addressMapping }}
                </div>
                <div class="commands">
                  <div
                    v-for="(item2, index2) in item"
                    :key="index2"
                    class="command"
                  >
                    <div class="status">
                      <StatusItem
                        v-for="(item3, index3) in item2.commandInfos"
                        :key="index3"
                        :statusValue="item3.statusValue"
                        :activeClassPrefix="
                          item3.statusName === '启动' ||
                          item3.statusName === '启用' ||
                          item3.statusName === '反馈'
                            ? 'active-circle-red'
                            : item3.statusName === '停止' ||
                              item3.statusName === '停用' ||
                              item3.statusName === '工作'
                            ? 'active-circle-green'
                            : 'active-circle-yellow'
                        "
                        :label="item3.statusName"
                        :isPanel="true"
                      />
                    </div>
                    <div class="handle">
                      <div
                        class="handle-button"
                        @click="onCommand(item2)"
                        :style="{
                          background:
                            item2.keyName === '启动'
                              ? '#f78989'
                              : item2.keyName === '停止'
                              ? '#67c23a'
                              : '#7367f0',
                        }"
                      >
                        {{ item2.keyName }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="un-config" @click="onConfig">配置</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <Config ref="refConfig" />
    <Add
      ref="refAdd"
      :itemInfo="dishInfo"
      :deviceInfo="deviceInfo"
      @update="onUpdate"
    />
    <ConfigList
      ref="refConfigList"
      :deviceInfo="deviceInfo"
      :dishInfo="dishInfo"
      @updateConfigList="updateConfigList"
    />

    <InstructPassword
      ref="refInstructPassword"
      :deviceInfo="deviceInfo"
      :statusInfo="statusInfo"
      :commandInfo="commandInfo"
      pageType="panel"
      @update="updatePanel"
    />

    <SetHostNumber
      ref="refSetHostNumber"
      :deviceInfo="deviceInfo"
      :statusInfo="statusInfo"
      @update="getDetectorDxtend"
    />
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  reqKeyCommandList,
  reqKeyCommandSend,
  reqDetectorDxtend,
} from "@/api/api";
import Config from "./Config.vue";
import Add from "./Config.vue";
import ConfigList from "./List.vue";
import StatusItem from "./StatusItem.vue";
import InstructPassword from "../InstructPassword.vue";
import SetHostNumber from "../SetHostNumber.vue";
export default {
  props: {
    deviceInfo: {
      type: Object,
      default: () => {},
    },
  },

  // inject: ["deviceInfo"],
  components: {
    Config,
    Add,
    ConfigList,
    StatusItem,
    InstructPassword,
    SetHostNumber,
  },
  data() {
    return {
      dishList: [
        {
          id: 1,
          name: "1号盘",
          active: true,
        },
        {
          id: 2,
          name: "2号盘",
          active: false,
        },
        {
          id: 3,
          name: "3号盘",
          active: false,
        },
        {
          id: 4,
          name: "4号盘",
          active: false,
        },
      ],

      commandData: {},
      list2Active: 0,
      list3Active: 0,
      list1: [],
      list2: [],
      list3: [],

      statusInfo: {
        fireAlarm: "", //火警状态：1-火警 0-未报警
        isMalfunction: "", //故障状态 0正常 1故障
        delayStatus: "", //延时状态：1-延时 0-延时结束
        sysFault: "", //系统故障：1-故障 0-已恢复
        bootUp: "", //启动状态：1-已启动 0-未启动
        mainCircuitWorked: "", //主电工作：1-工作 0-未工作
        feedback: "", //反馈状态：1-已反馈 0-未反馈
        backupCircuitWorked: "", //备电工作：1-工作 0-未工作
        isolate: "", //隔离（屏蔽）状态：1-隔离（屏蔽） 0-未隔离（屏蔽）
        supervise: "", //监管状态：1-监管 0-未监管

        fireFeedback: "", //火警传输 (动作)反馈状态: 1-口反馈 0-未反馈
        fireIsolate: "", //火警传输 隔离(屏蔽)状态:1-隔离(屏蔽)0-未隔离

        sprayRequest: "", //喷洒状态：1-喷洒允许 0-喷洒禁止
        gasSpraying: "", //喷洒状态：1-喷洒中 0-未喷洒

        audibleVisualMute: "", //声光报警 消音状态:1-已消音 0-未消音
        audibleVisualIsolate: "", //声光报警 隔离(屏蔽)状态:1-隔离(屏蔽)0-未隔离
        audibleVisualFault: "", //声光报警 故障:1-故障 0-已恢复
      },

      dishInfo: {}, //一个盘号信息

      commandInfo: {}, //一个指令信息
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  created() {},
  mounted() {},
  watch: {},
  methods: {
    // 新增
    onAdd(id) {
      let { list2Active, list3Active } = this;
      let dishInfo = {};
      switch (id) {
        case 1:
          dishInfo.layoutType = 1;
          dishInfo.panelNo = 1;
          break;
        case 2:
          dishInfo.layoutType = 2;
          dishInfo.panelNo = list2Active + 1;
          break;
        case 3:
          dishInfo.layoutType = 3;
          dishInfo.panelNo = list3Active + 1;
          break;
      }
      this.dishInfo = dishInfo;
      this.$refs.refAdd.dialogVisible = true;
    },
    // 配置
    onConfig(id, isUpdate = false) {
      let { commandData, list2Active, list3Active } = this;
      let dishInfo = {};
      switch (id) {
        case 1:
          dishInfo = {
            layoutType: 1,
            panelNo: 1,
            dataList: commandData.list1,
          };
          break;
        case 2:
          dishInfo = {
            layoutType: 2,
            panelNo: list2Active + 1,
            dataList:
              commandData?.list2?.[list2Active]?.reduce(
                (acc, curr) => acc.concat(curr),
                []
              ) ?? [],
          };
          break;
        case 3:
          dishInfo = {
            layoutType: 3,
            panelNo: list3Active + 1,
            dataList:
              commandData?.list3?.[list3Active]?.reduce(
                (acc, curr) => acc.concat(curr),
                []
              ) ?? [],
          };
          break;
      }
      this.dishInfo = dishInfo;

      if (isUpdate) return;
      this.$refs.refConfigList.dialogVisible = true;
    },
    // 更新
    async updateConfigList() {
      await this.getKeyCommandList();
      await this.onConfig(this.dishInfo.layoutType, true);
    },
    onUpdate() {
      this.getKeyCommandList();
    },
    // 点击盘号
    onDish(id, index) {
      switch (id) {
        case 2:
          this.list2Active = index;
          break;
        case 3:
          this.list3Active = index;
          break;
      }
    },
    // 状态信息
    async getDetectorDxtend() {
      let res = await reqDetectorDxtend({
        deviceCode: this.deviceInfo.imei || this.deviceInfo.deviceCode,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.statusInfo = res.data.detail;
    },
    // 获取指令列表
    async getKeyCommandList() {
      let res = await reqKeyCommandList({
        deviceCode: this.deviceInfo.imei || this.deviceInfo.deviceCode,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let list = res.data.list;
      if (list && list.length) {
        let commandData = this.processData(list);
        if (commandData.list1 && commandData.list1.length) {
          commandData.list1 = commandData.list1[0].reduce(
            (acc, curr) => acc.concat(curr),
            []
          );
        }
        this.commandData = commandData;
      } else {
        this.commandData = {
          list1: [],
          list2: [],
          list3: [],
        };
      }
    },

    processData(dataList) {
      // 初始化结果结构
      const result = {
        list1: [],
        list2: [],
        list3: [],
      };

      // 按 layoutType 分组
      const layoutGroups = {
        1: [],
        2: [],
        3: [],
      };

      dataList.forEach((item) => {
        const layoutType = item.layoutType;
        if (["1", "2", "3"].includes(layoutType)) {
          layoutGroups[layoutType].push(item);
        }
      });

      // 处理每个 layoutType 分组
      ["1", "2", "3"].forEach((layoutType) => {
        const listKey = `list${layoutType}`;
        const items = layoutGroups[layoutType];

        // 按 panelNo 分组
        const panelMap = {};
        items.forEach((item) => {
          const panelNo = item.panelNo;
          if (!panelMap[panelNo]) panelMap[panelNo] = {};
          const groupNo = item.groupNo;

          if (!panelMap[panelNo][groupNo]) {
            panelMap[panelNo][groupNo] = [];
          }
          panelMap[panelNo][groupNo].push(item);
        });

        // 处理 panelNo 排序和结构
        const sortedPanels = Object.keys(panelMap)
          .sort((a, b) => parseInt(a) - parseInt(b))
          .map((panelKey) => {
            // 处理 groupNo 排序
            const groups = panelMap[panelKey];
            return Object.keys(groups)
              .sort((a, b) => parseInt(a) - parseInt(b))
              .map((groupKey) => {
                // 按 keyNo 排序
                return groups[groupKey].sort(
                  (a, b) => parseInt(a.keyNo) - parseInt(b.keyNo)
                );
              });
          });

        result[listKey] = sortedPanels;
      });

      return result;
    },
    // 下发指令
    async onCommand(item) {
      console.log(item,222);
      if (this.deviceInfo.protocol == 7 && !this.statusInfo.hostNumber) {
        this.$modal.notifyWarning("请先设置主机号");
        setTimeout(() => {
          this.$refs.refSetHostNumber.dialogVisible = true;
        }, 500);
        return;
      }
      if (item.layoutType == 1) {
        const result = await this.$confirm(
          `此操作将下发 ${item.keyName} 指令, 是否继续?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).catch(() => {});
        if (result !== "confirm") return;
        this.keyCommandSendFoo(item);
      } else {
        this.commandInfo = JSON.parse(JSON.stringify(item));
        this.$refs.refInstructPassword.dialogVisible = true;
      }
    },

    async keyCommandSendFoo(item) {
      let res = await reqKeyCommandSend({
        deviceCode: this.deviceInfo.imei || this.deviceInfo.deviceCode,
        id: item.id,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("指令下发成功");
      setTimeout(() => {
        this.getDetectorDxtend();
        this.getKeyCommandList();
      }, 3000);
    },

    updatePanel() {
      setTimeout(() => {
        this.getDetectorDxtend();
        this.getKeyCommandList();
      }, 3000);
    },
  },
};
</script>


<style lang="less" scoped>
:root {
  --item-width-base: 220px; /* 基础宽度 */
  --item-margin: 10px; /* 子元素之间的间距 */
}
.container {
  height: 100%;
  color: @primaryThemeTxtColor4;
  font-size: 14px;
  overflow-y: auto;

  .row1 {
    display: flex;
    padding: 0 20px;

    .div-box1 {
      flex: 3;
      margin: 0 10px;
    }
    .div-box2 {
      flex: 1;
      margin: 0 10px;
    }

    .div-box {
      background: @primaryBorderColor3;
      border-radius: 15px;
      padding: 20px 20px 20px;
      margin-top: 20px;
      box-sizing: border-box;
      position: relative;

      .head {
        font-size: 16px;
        color: #7367f0;
        font-weight: 600;
        margin-bottom: 5px;
      }
      .content {
        display: flex;
        flex-wrap: wrap;

        .group {
          width: 100%;
          margin: 8px 0;
          background: @primaryBgcolor10;
          border-radius: 5px;
          display: flex;
          align-items: center;
          .title {
            min-width: 110px;
            padding: 0 10px 0 20px;
          }
        }
        .group-button {
          margin-top: 6px;
          display: flex;
          flex-wrap: wrap;
          .button-box {
            margin: 0 10px 10px 0;
            .button {
              margin: 5px 0;
            }
          }
        }
      }
    }
  }

  .row2 {
    display: flex;
    padding: 0 20px;
    margin-bottom: 20px;

    .div-box1 {
      flex: 1;
      margin: 0 10px;
    }
    .div-box2 {
      flex: 1;
      margin: 0 10px;
    }

    .div-box {
      background: @primaryBorderColor3;
      border-radius: 15px;
      padding: 20px 20px 20px;
      box-sizing: border-box;
      margin-top: 20px;
      position: relative;

      &:last-child {
      }

      .content {
        display: flex;
        flex-wrap: wrap;

        .item {
          position: relative;
          height: 130px;
          // padding: 20px 2px;
          margin: 5px 0;
          border: 1px solid @primaryBorderColor2;
          border-radius: 8px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          .index {
            position: absolute;
            top: 5px;
            left: 5px;
            color: @primaryTxtcolortab;
          }

          .commands {
            margin-top: 15px;
            display: flex;
            align-items: center;
            .command {
              flex: 1;
              .status {
                min-width: 10px;
                font-size: 12px;
                display: flex;
                justify-content: center;
                flex-wrap: wrap;
              }
            }

            .command:nth-child(2) {
              border-left: 1px solid @primaryBorderColor2;
              padding-left: 15px;
              margin-left: 15px;
            }
          }

          .handle {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            .handle-button {
              width: 100px;
              height: 28px;
              line-height: 28px;
              text-align: center;
              color: #ffffff;
              cursor: pointer;
              border-radius: 3px;
              background: #7367f0;

              &:hover {
                opacity: 0.9;
              }
            }
          }

          .un-config {
            text-align: center;
            line-height: 100px;
            cursor: pointer;
          }
        }
      }
    }
  }

  // 头
  .head {
    width: 100%;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .head-left {
      display: flex;
      align-items: center;
      .title {
        font-size: 16px;
        color: #7367f0;
        font-weight: 600;
        white-space: nowrap;
        margin-right: 20px;
      }
      .dish-box {
        display: flex;
        border-radius: 5px;
        overflow-x: auto;

        .dish {
          width: 60px;
          min-width: 60px;
          cursor: pointer;
          color: @primaryTxtcolortab;
          border: 1px solid @primaryBorderColor6;
          padding: 4px 1px;
          display: flex;
          align-items: center;
          justify-content: center;
          &:hover {
            opacity: 0.8;
          }
          &:first-child {
            border-radius: 5px 0 0 5px;
          }
          &:last-child {
            border-radius: 0 5px 5px 0;
          }
        }
        .dish-active {
          color: #fff;
          background: #7367f0;
        }
      }
    }
    .head-right {
      margin-left: 20px;
      display: flex;
      align-items: center;
    }
  }
}

// 媒体查询
@media screen and (max-width: 1040px) {
  .row1 {
    display: block !important;
  }
  .row2 {
    display: block !important;
  }
}

::v-deep .el-button.el-button--default {
  // background: #f56c6c;
  // border: 1px solid #f56c6c;
  color: #d1d1d1;
}

::v-deep .el-button.el-button--primary {
  // background: #f56c6c !important;
  // border: 1px solid #00edfe;
  color: #d1d1d1;
}
</style>